package nu.boomboom.smartfsync;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;

public class FileManipulator {

	private final File baseDir;
	private String charset = Charset.defaultCharset().name();

	public FileManipulator() {
		baseDir = new File("target/tmp");
		if (baseDir.exists()) {
			cleanUpDir(baseDir);
			baseDir.delete();
		}
		baseDir.mkdir();

	}

	private void cleanUpDir(File dir) {
		for (File file : dir.listFiles()) {
			if (file.isDirectory()) {
				cleanUpDir(file);
			}
			file.delete();
		}
	}

	public FileManipulator(String charset) {
		this();
		this.charset = charset;

	}

	public void manipulateFiles(Creator creator) throws IOException {
		creator.setFileManuplator(this);
		creator.manipulateFiles();
	}

	public FileManipulator newFile(String path, byte[] content)
			throws IOException {
		File file = new File(baseDir, path);
		OutputStream out = null;
		try {
			out = new FileOutputStream(file);
			out.write(content);
		} finally {
			if (out != null)
				out.close();
		}
		return this;
	}

	public FileManipulator newFile(String path, String content)
			throws IOException {
		return newFile(path, content.getBytes(charset));
	}

	public FileManipulator newDir(String path) {
		File dir = new File(baseDir, path);
		dir.mkdir();
		return this;
	}

	public FileManipulator newDirs(String... paths) {
		for (String path : paths) {
			newDir(path);
		}
		return this;
	}

	public File baseDir() {
		return baseDir;
	}

	abstract public static class Creator {
		private FileManipulator manipulator;

		void setFileManuplator(FileManipulator manipulator) {
			this.manipulator = manipulator;
		}

		public abstract void manipulateFiles() throws IOException;

		public void newFile(String path, byte[] content) throws IOException {
			manipulator.newFile(path, content);
		}

		public void newFile(String path, String content) throws IOException {
			manipulator.newFile(path, content);
		}

		public void newDir(String path) {
			manipulator.newDir(path);
		}

		public void newDirs(String... paths) {
			manipulator.newDirs(paths);
		}
	}

}
